﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Simple.Services.System
{
    public class ChildAttendanceRuleService : BusinessBaseService
    {
        private readonly SimpleDbContext _context;

        public ChildAttendanceRuleService(SimpleDbContext context,
            ISimpleService services) : base(services)
        {
            _context = context;
        }

        public async Task<ChildAttendanceRuleDto> GetAsync()
        {
            var rule = await (await OrganizationFilter(_context.Set<ChildAttendanceRule>())).OrderByDescending(p => p.CreatedTime).FirstOrDefaultAsync();
            if (rule == null)
            {
                return new ChildAttendanceRuleDto();
            }
            var result = new ChildAttendanceRuleDto()
            {
                EntryTime = $"{rule.EntryTime.Value.Hour}:{rule.EntryTime.Value.Minute}",
                OutSchoolTime = $"{rule.OutSchoolTime.Value.Hour}:{rule.OutSchoolTime.Value.Minute}"
            };
            return MapperHelper.Map<ChildAttendanceRuleDto>(result);
        }

        public async Task<int> CreateNewRule(CreateChildAttendanceRuleInput input)
        {
            ChildAttendanceRule rule = new ChildAttendanceRule()
            {
                EntryTime = Convert.ToDateTime(input.EntryTime),
                OutSchoolTime = Convert.ToDateTime(input.OutSchoolTime)
            };

            var entityChild = await _context.AddAsync(rule);

            return await _context.SaveChangesAsync();
        }
    }
}
